from tornado.web import authenticated
from common.BaseHandler import BaseHandler
from common.Models import Tag, PostTagMiddle


class TagHandler(BaseHandler):
    @authenticated
    def get(self):
        if "api" in self.request.uri:
            result = self.result()
            data = self.get_params()
            page = int(data.get("page", 1))
            limit = int(data.get("limit", 5))
            try:
                tags = self.session.query(Tag).filter_by(author_id=self.current_user, is_delete=0)
                data_count = tags.count()
                tags = tags.order_by(Tag.create_time.desc()).limit(limit).offset((page-1)*limit).all()
                data_list = []
                for tag in tags:
                    data_list.append({
                        "id": tag.id,
                        "name": tag.name,
                        "post_count": self.session.query(PostTagMiddle).filter_by(tag_id=tag.id).count(),
                        "create_time": str(tag.create_time)
                    })

                result["status"] = 1
                result["msg"] = "获取数据成功"
                result["data"] = {
                    "data_count": data_count,
                    "data_list": data_list
                }
            except Exception as e:
                self.logger.error(e)
                result = self.check_except_zh(e, msg="数据查询失败！")
            self.write(result)
        else:
            self.render("management/tag.html")

    @authenticated
    def post(self):
        result = self.result()
        data = self.get_body()
        try:
            name = self.data_null(data, "tag_name", "请输入名称！")
            obj_exist = self.session.query(Tag).filter_by(name=name, author_id=self.current_user, is_delete=0).count()
            if obj_exist > 0:
                self.data_except("当前标签已存在！")
            new_tag = Tag(name=name, author_id=self.current_user)
            self.session.add(new_tag)
            self.session.commit()
            result["status"] = 1
            result["msg"] = "新增标签成功"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e, msg="新增标签失败！")
        self.write(result)

    @authenticated
    def put(self):
        result = self.result()
        data = self.get_body()
        try:
            tag_id = self.data_null(data, "tag_id", "请选择要更改的标签！")
            name = self.data_null(data, "tag_name", "请输入名称！")
            tag_obj = self.session.query(Tag).filter_by(id=tag_id, author_id=self.current_user, is_delete=0).first()
            if not tag_obj:
                self.data_except("当前选择的标签不存在！")
            name_exist = self.session.query(Tag).filter(Tag.id != tag_id).filter_by(name=name, author_id=self.current_user, is_delete=0).count()
            if name_exist > 0:
                self.data_except("当前标签名称已存在！")
            if tag_obj.name != name:
                tag_obj.name = name
                self.session.commit()
            result["status"] = 1
            result["msg"] = "更改标签名称成功"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e, msg="更改标签名称失败！")
        self.write(result)

    @authenticated
    def delete(self):
        result = self.result()
        data = self.get_body()
        try:
            tag_id = self.data_null(data, "tag_id", "请选择要删除的标签！")
            tag_obj = self.session.query(Tag).filter_by(id=tag_id, author_id=self.current_user, is_delete=0).first()
            if not tag_obj:
                self.data_except("当前选择的标签不存在！")
            post_count = self.session.query(PostTagMiddle).filter_by(tag_id=int(tag_id)).count()
            if post_count > 0:
                self.data_except("当前标签存在博文关联，无法删除！")
            tag_obj.is_delete = 1
            self.session.commit()
            result["status"] = 1
            result["msg"] = "删除标签成功！"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e, msg="删除标签成功！")
        self.write(result)


